const {Controller} = require("ee-core");
const Addon = require('ee-core/addon');
const HttpClient = require('ee-core/httpclient');
const Cross = require('ee-core/cross');
const {MUtils} = require("../utils/MUtils");
const {LockUtil} = require("../utils/LockUtil");
const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36";

const serverUrl = "http://127.0.0.1:7073";


/**
 * 子窗口
 * @type {{}}
 */
let subWin = {};
let CHECK_LOGIN_STATUS_KEY = 'CHECK_LOGIN_STATUS_KEY';
class PbController extends Controller {

    constructor(ctx) {
        super(ctx);
    }

    createPbWindow(args) {
        const {type, contentUrl,userName,password, windowName, windowTitle, windowsId} = args;

        let accountWin = subWin[windowsId];
        if (accountWin != null) {
            accountWin.destroy();
        }

        console.log('contentUrl: ', contentUrl);
        let opt = {
            title: windowTitle,
            width: 1000,
            height: 300,
            frame: true,
            x: 0,
            y: 600,
            webPreferences: {
                webSecurity: false,
                nodeIntegration: false,
                contextIsolation: false,
                userAgent: USER_AGENT,
                backgroundColor: '#000000',
            }

        }
        const win = Addon.get('window').create(windowName, opt);
        const winContentsId = win.webContents.id;
        // load page
        win.loadURL(contentUrl, {userAgent: USER_AGENT}).then(r => console.log(r));

        win.on('closed', () => {
            subWin[winContentsId] = null
        });
        const hc = new HttpClient();
        const lockFlag = LockUtil.lock(CHECK_LOGIN_STATUS_KEY, 10000);

        // 监听过滤器
        win.webContents.session.webRequest.onBeforeSendHeaders(async (details, callback) => {
            // 获取请求路径
            const targetUrl = details.url;
            // 获取请求头
            const targetHeader = details.requestHeaders;
            // 强制设置请求头的User_Agent
            details.requestHeaders['User-Agent'] = USER_AGENT;

            // 根据平台处理拦截
            if (targetUrl != null
                && targetHeader != null) {
                const cookie = targetHeader['Cookie'];
                const host = getHost(targetUrl);
                const userAgent = targetHeader['User-Agent'];
                const referer = targetHeader['Referer'];
                if (host != null && cookie != null) {
                    if (!lockFlag) {
                        console.log('刷新平博窗口失败=>获取锁失败！！！');
                        return;
                    }
                    try {
                        // 向golang服务发送http请求
                        const options = {
                            method: 'POST',
                            data: {"cookie": cookie, "host": host, "userAgent": userAgent, "referer": referer},
                            dataType: 'json',
                            timeout: 5000,
                        };
                        const result = await hc.request(serverUrl + "/pb/setSession", options);
                        console.log("刷新pb session成功:",result)
                    } finally {
                        LockUtil.unLock(CHECK_LOGIN_STATUS_KEY);
                    }


                }
            }

            // 放行请求
            callback({cancel: false, requestHeaders: details.requestHeaders});
        });


        // 监听 new-window-for-tab 事件
        win.webContents.on('did-start-loading', (event, url, frameName, disposition, options) => {

            // 页面加载完成后执行登录逻辑
            win.webContents.executeJavaScript(`
                        window.process=undefined;
                `, true).then((global) => {
                console.log('JavaScript executed successfully');
            }).catch((error) => {
                console.error('JavaScript execution failed:', error);
            });
        })


        // 平博自动登录逻辑
        if (MUtils.isNotEmpty(userName) && MUtils.isNotEmpty(password)) {
            win.webContents.on('did-finish-load', () => {
                // 页面加载完成后执行登录逻辑
                win.webContents.executeJavaScript(`
                        const timer = setInterval(function() {
                            const loginId = document.querySelector('input[id="loginId"]');
                            if (loginId != null) {
                                clearInterval(timer);
                                console.log('设置账号密码');
                                document.querySelector('input[id="loginId"]').value = "${userName}";
                                document.querySelector('input[id="pass"]').value = "${password}";
                                setTimeout(function() {
                                    const submitButton = document.querySelector('.LoginComponent .form-inline button[type="submit"]');
                                    if (submitButton) {
                                        submitButton.click();
                                    } else {
                                        console.error('Form element not found');
                                    }
                                }, 500);
                            }
                        }, 1000);
                `, true).then((global) => {
                    console.log('JavaScript executed successfully');
                }).catch((error) => {
                    console.error('JavaScript execution failed:', error);
                });
            });
        }


        subWin[winContentsId] = win
        return winContentsId;
    }

}

/**
 * 解析主机地址
 *
 * @param url
 * @returns {string}
 */
function getHost(url) {
    const parsedUrl = new URL(url);
    return parsedUrl.hostname;
}

PbController.toString = () => '[class PbController]';
module.exports = PbController;